package com.wfh.aigenerator.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.wfh.aigenerator.common.ErrorCode;
import com.wfh.aigenerator.constant.UserConstant;
import com.wfh.aigenerator.exception.BusinessException;
import com.wfh.aigenerator.model.dto.UserLoginRequest;
import com.wfh.aigenerator.model.dto.UserQueryRequest;
import com.wfh.aigenerator.model.dto.UserRegisterRequest;
import com.wfh.aigenerator.model.entity.User;
import com.wfh.aigenerator.mapper.UserMapper;
import com.wfh.aigenerator.model.enums.UserRoleEnum;
import com.wfh.aigenerator.model.vo.UserVO;
import com.wfh.aigenerator.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.security.Signature;
import java.util.List;

/**
 * 用户表 服务层实现。
 *
 * @author wangfenghuan
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService {

    /**
     * 用户注册
     *
     * @param request
     * @return
     */
    @Override
    public long userRegister(UserRegisterRequest request) {
        // 校验参数
        String userAccount = request.getUserAccount();
        String userPassword = request.getUserPassword();
        String checkPassword = request.getCheckPassword();
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查询用户名和密码是否存在
        long account = this.mapper.selectCountByQuery(new QueryWrapper().eq("userAccount", userAccount));
        if (account > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
        // 对密码进行加密
        String newPwd = DigestUtil.md5Hex(userPassword);
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(newPwd);
        user.setUserName("test01");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(user);
        if (!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户注册失败");
        }
        return user.getId();
    }

    /**
     * 获取登录用户的vo对象
     *
     * @param user
     * @return
     */
    @Override
    public UserVO getLoginUserVo(User user) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取uservolist
     *
     * @param users
     * @return
     */
    @Override
    public List<UserVO> getUserVoList(List<User> users) {
        return users.stream().map(user -> BeanUtil.copyProperties(user, UserVO.class)).toList();
    }

    /**
     * 获取查询包装类
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper getUserWrapper(UserQueryRequest userQueryRequest) {
        QueryWrapper queryWrapper = new QueryWrapper();
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();

        return queryWrapper.eq("id", id, ObjUtil.isNotEmpty(id))
                .eq("userAccount", userAccount, ObjUtil.isNotEmpty(userAccount))
                .like("userName", userName, ObjUtil.isNotEmpty(userName))
                .like("userProfile", userProfile, ObjUtil.isNotEmpty(userProfile))
                .eq("userRole", userRole, ObjUtil.isNotEmpty(userRole));
    }

    /**
     * 用户登录
     *
     * @param request
     * @param httpServletRequest
     * @return
     */
    @Override
    public UserVO userLogin(UserLoginRequest request, HttpServletRequest httpServletRequest) {
        // 校验参数
        String userAccount = request.getUserAccount();
        String userPassword = request.getUserPassword();
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 加密
        String newPwd = DigestUtil.md5Hex(userPassword);
        // 查询用户名和密码是否存在
        User user = this.mapper.selectOneByQuery(new QueryWrapper().eq("userAccount", userAccount).eq("userPassword", newPwd));
        if (user == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户不存在");
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        httpServletRequest.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return userVO;
    }

    /**
     * 获取当前登录用户
     *
     * @param httpServletRequest
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest httpServletRequest) {
        User attribute = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (attribute == null || attribute.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long id = attribute.getId();
        User user = this.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }

    /**
     * 退出登录
     * @param httpServletRequest
     * @return
     */
    @Override
    public Boolean userLogout(HttpServletRequest httpServletRequest) {
        User user = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user != null) {
            httpServletRequest.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
            return true;
        }
        return false;
    }

    @Override
    public UserVO getUserVO(User user){
        return BeanUtil.copyProperties(user, UserVO.class);
    }
}
